//app.js
const allUrl = require('/config').allUrl
var newCallAudioUrl = 'https://wujustudio.com/Public/mp3/newCase.mp3'
var wushengAudioUrl = 'https://wujustudio.com/Public/mp3/wusheng.mp3'
var util = require('/utils/util.js')

App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)
    //  同步民警位置信息
    // this.asyncPolicePosition()
  },
  onShow: function(){
    // if(this.globalData.j_id){
    //   this.playNewCallAudio()
      //  同步民警位置信息
      // this.asyncPolicePosition()
    // }
    var that = this
    wx.onBackgroundAudioStop(function () {
      that.playNewCallAudio()
    })
  },
  onHide: function(){
    if(this.globalData.j_id){
      this.playNewCallAudio()
    } 
    var that = this
    wx.onBackgroundAudioStop(function () {
      that.playNewCallAudio()
    })
  },

  //  获取用户信息
  getUserInfo:function(cb, successCallback){
    var that = this
    var code = ''

    wx.login({
      success: function(login_res){
        //  记录code
        code = login_res.code
        if(that.globalData.userInfo){
          typeof cb == "function" && cb(that.globalData.userInfo)
          //  获取openid
          that.policeOpenid(code, that.globalData.userInfo, successCallback)
        }else{
          wx.getUserInfo({
            success: function (userInfo_res) {
              that.globalData.userInfo = userInfo_res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
              // 获取openid
              that.policeOpenid(code, userInfo_res.userInfo, successCallback)
            }
          })
        }
      },
      fail: function(login_res) {},
      complete: function(login_res) {}
    })
  },
  //  发送请求openid
  policeOpenid: function(code, userInfo, successCallback){
    var that = this
    var data = {
      code: code,
      nickName: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      gender: userInfo.gender,
      province: userInfo.province,
      city: userInfo.city,
      country: userInfo.country
    }
    wx.request({
      url: allUrl + 'Api/getPoliceOpenid.html',
      data: data,
      method: 'POST', 
      header:{
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function(res){
        // console.log('-----0.0--------')
        // console.log(allUrl + 'Api/getPoliceOpenid.html')
        // console.log(res.data.data)
        that.globalData.openid = res.data.data.openid
        that.globalData.j_id = res.data.data.j_id
        that.globalData.call_id = res.data.data.call_id
        successCallback(res)
      },
      fail: function(res) {},
      complete: function(res) {}
    })
  },


  //  *****同步民警位置********
  asyncPolicePosition: function(){
    console.log('1----->同步民警位置')
    var that = this
    setTimeout(function(){
      if(that.globalData.j_id){//如果有警员id，
        // if(that.globalData.call_id==null){//如果没有正在处理的案件，同步请求新的案件
          //  1.获取最新分派案件
          that.getCallNearest()
        // }
        //  2.获取位置，发送民警位置信息
        wx.getLocation({
          type: 'gcj02', 
          success: function(res){
            //发送位置信息
            that.sendPoliceLocaltion(res.latitude, res.longitude)
          },
          fail: function(res) {//位置获取失败，重新发送
            that.asyncPolicePosition()
          },
          complete: function(res) {}
        })
      // }else{//如果没有警员id，继续循环
      //   that.asyncPolicePosition()
      }
    }, 3000);
  },
  sendPoliceLocaltion: function(j_lat, j_lng){
    console.log('发送一次民警位置信息')
    var that = this
    wx.request({
      url: allUrl + 'Api/setPolicePosition.html',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        j_id: that.globalData.j_id,
        j_lng: j_lng,
        j_lat: j_lat
      },
      method: 'POST', 
      success: function(res){},
      fail: function(res) {},
      complete: function(res) {
        that.asyncPolicePosition()
      }
    })
  },
  //   ********获取最新分派案件*********
  getCallNearest: function(){
    console.log('2----->获取最新分派案件')
    var that = this
    wx.request({
      url: allUrl + 'Api/getCallNearest.html',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        j_id: that.globalData.j_id
      },
      method: 'POST', 
      success: function(res){
        // console.log('app   新案件')
        // console.log(res)
        //  弹出对话框，可以跳转
        if(res.data.status_code == 200 && res.data.data.call){
          if (that.globalData.call_id == res.data.data.call.call_id){
            return
          }
          that.globalData.call_id = res.data.data.call.call_id
          var one = res.data.data.call
          that.globalData.alertAudio = true
          // that.vibratePlay()
          that.playNewCallAudio()
          wx.showModal({
            title:'您有新案件未处理',
            content: '报警地点:'+one.address+'\n报警信息:'+one.remark+'\n报警时间:'+one.created_at+'\n报警人电话:'+one.mobile,
            showCancel: false,
            confirmText: '去处理',
            success: function(model_res){
              if(model_res.confirm){
                that.globalData.alertAudio = false
                wx.stopBackgroundAudio()
                wx.navigateTo({
                  url: '../case/case?latitude=' + one.lat + '&longitude=' + one.lng + '&isDone=' + one.status + '&alertPhone=' + one.mobile + '&call_id=' + one.call_id + '&address=' + one.address + '&remark=' + one.remark + '&created_at=' + one.created_at,
                  success: function(res){},
                  fail: function(res) {},
                  complete: function(res) {}
                })
              }
            }
          })
        }
      },
      fail: function(res) {},
      complete: function(res) {}
    })
  },



  // 展示弹出框
  showSomeModel: function(title, content, sucBack, errBack, complete){
    var that = this
    wx.showModal({
      title: title,
      content: content,
      cancelText: '取消',
      confirmText: '确定',
      success: function(res){
         if(res.confirm){
            sucBack()
         }else{
           errBack()
         }
      },
      complete: function(res){
        complete()
      }
    })
  },
  showSomeModel1: function(title, content, confirmText, sucBack, errBack, complete){
    var that = this
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      confirmText: confirmText,
      success: function(res){
         if(res.confirm){
            sucBack()
         }else{
           errBack()
         }
      },
      complete: function(res){
        complete()
      }
    })
  },


  //  播放来新案件音频
  playNewCallAudio: function () {
    var that = this
    console.log('开始播放音乐' + util.formatTime(new Date()))
    console.log('开始播放音乐' + that.globalData.alertAudio ? newCallAudioUrl : wushengAudioUrl)
    
    wx.playBackgroundAudio({
      dataUrl: that.globalData.alertAudio?newCallAudioUrl:wushengAudioUrl,
      title: '新案件',
      success: function (res) { 
        // console.log('成功播放音乐' + util.formatTime(new Date())) 
      },
      fail: function () { 
        // console.log('失败播放音乐' + util.formatTime(new Date())) 
      },
      complete: function (audio_res) {
        // console.log('完成播放音乐' + util.formatTime(new Date()))
        // wx.onBackgroundAudioStop(function () {
          // if (that.globalData.alertAudio) {
            // that.playNewCallAudio()
          // }
        // })
      }
    })
  },
  vibratePlay: function(){
    var that = this
    if (wx.vibrateLong) {
      wx.vibrateLong({
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { 
          // if (that.globalData.alertAudio) {
          //   setTimeout(function () {
          //     that.vibratePlay()
          //   }, 2000)
          // }
        }
      })
    } else {
      console.log('不支持')
    }
  },
  


  globalData:{
    userInfo:null,  //  用户信息
    openid: null, //警员openid
    j_id: null, // 警员id
    call_id: null, //正在处理案件的id

    first: true,  //如果为true，index页面可以执行onShow，否则不能执行，避免重复执行
    alertAudio: false,  //如果为true，播放有声音乐
  }
})